package com.wanghua.mall.order.config;

import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * RabbitMQ的简单应用
 * @author wanghua
 * @create 2021-09-07 18:39
 */
@Configuration
public class RabbitConfig {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制RabbitTemplate
     * 1、服务收到消息就会回调
     * 1、spring.publisher-confirm-type: correlated
     * 2、设置确认回调
     * 2、消息正确抵达队列就会进行回调
     * 1、spring.rabbitmq.publisher-returns: true
     * spring.rabbitmq.template.mandatory: true
     * 2、设置确认回调ReturnCallback
     * <p>
     * 3、消费端确认(保证每个消息都被正确消费，此时才可以broker删除这个消息)
     */
    // @PostConstruct  //MyRabbitConfig对象创建完成以后，执行这个方法
    @PostConstruct
    public void initRabbitTemplate() {

        //发送端消息抵达Broker确认
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * 1、只要消息抵达Broker就ack=true
             * @param correlationData：当前消息的唯一关联数据(这个是消息的唯一id)
             * @param ack：消息是否成功收到
             * @param cause：失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("confirm...correlationData[" + correlationData + "]==>ack:[" + ack + "]==>cause:[" + cause + "]");
            }
        });

        //发送端消息抵达队列确认
        rabbitTemplate.setReturnsCallback((new RabbitTemplate.ReturnsCallback() {
            /**
             * 只要消息没有投递给指定的队列(即无法路由)，就触发这个失败回调
             * message：投递失败的消息详细信息
             * replyCode：回复的状态码
             * replyText：回复的文本内容
             * exchange：当时这个消息发给哪个交换机
             * routingKey：当时这个消息用哪个路邮键
             */
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("Fail Message[" + returnedMessage.getMessage() +
                        "]==>replyCode[" + returnedMessage.getReplyCode() +
                        "]==>replyText[" + returnedMessage.getReplyText() +
                        "]==>exchange[" + returnedMessage.getExchange() +
                        "]==>routingKey[" + returnedMessage.getRoutingKey() + "]");
            }
        }));


    }
}
